<?php

namespace App\Http\Controllers\admin;

use App\Models\Role;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use function PHPUnit\Framework\exactly;


class UserController extends Controller
{
    /**
     * 登录页
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function index()
    {

        return view('admin/index/login');
    }

    /**
     * 执行登录
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function login(Request $request)
    {
        $params = $request->except('_token');

        //验证信息
        $post = $request->validate([
            'username' => 'required',
            'password' => 'required',
        ],[
            'username.required'=>'用户名不能为空',
            'password.required'=>'密码不能为空',
        ]);

        //验证信息
        //验证用户名密码是否正确
        $bool=auth()->attempt($post);

        if($bool){
            //判断用户是否超级管理员
            $auth = auth()->user()->username;
            //判断用户是否超级管理登录
            if($auth == config('rbac.super')){
                session(['admin_auths'=>true]);
            }else{

                //获取用户角色
                $role = auth()->user()->role;
                //获取用户权限
                $node = $role->nodes->pluck('route_name','id')->toArray();

                //缓存用户权限到session
                session(['admin_auths'=>$node]);
            }

            //登录成功跳转首页
            return redirect(route('admin.index'));
        }

        //登录失败返回
        return redirect(route('login'))->withErrors('用户名或密码错误');

    }

    /**
     * 退出登录
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function loginOut()
    {
        \auth()->logout();
        //返回登录页 with 缓存session
        return redirect(route('login'))->with('loginout','请重新登录');
    }

    /**
     * 用户展示页
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function userList()
    {

        $data = User::withTrashed()->paginate(8);


        return view('admin/user/userList',compact('data'));
    }

    /**
     * 删除用户..
     * @param Request $request
     * @return array
     */
    public function userDel(Request $request,User $user)
    {
        $id = $request->get('id');

        if(is_array($id)){
            foreach ($id as $key=>$val){
                if(!is_numeric($val)){
                    return ['status'=>0,'msg'=>'参数错误'];
                }
            }
        }else if(!is_numeric($id)){
            return ['status'=>0,'msg'=>'参数错误'];
        }


        $res = User::destroy($id);

        if($res){
            return ['status'=>1,'msg'=>'删除成功'];
        }

        return  ['status'=>0,'msg'=>'删除失败'];
    }

    /**
     * 恢复删除用户
     */

    public function userrestory(Request $request)
    {
        $id = $request->get('id');
        $res = User::where('id',$id)->restore();

        if($res){
            return ['status'=>1,'msg'=>'恢复成功','error_code'=>200];
        }else{
            return ['status'=>0,'msg'=>'恢复失败','error_code'=>10001];
        }
    }

    /**
     * 添加页
     */
    public function user()
    {

        return view('admin.user.useradd');
    }

    /**
     * 添加用户
     */
    public  function userAdd(Request $request)
    {
        $params = $request->except('_token');

        $data = $request->validate([
            'username' => 'required',
            'truename' => 'required',
            'password' => 'required',
//            'password2' => 'required',
            'sex' => 'required',
            'email' => 'required',
            'phone' => 'required',
        ],[
            'username.required'=>'用户名不能为空',
            'truename.required'=>'真实姓名不能为空',
            'password.required'=>'密码不能为空',
//            'password2.required'=>'确认密码不能为空',
            'sex.required'=>'性别不能为空',
            'email.required'=>'邮箱不能为空',
            'phone.required'=>'手机号不能为空',
        ]);

        //send(1,2) 必须有页面 参数1：页面的地址 参数2：发送的内容
        \Mail::send('admin.user.email',$params,function (\Illuminate\Mail\Message $message ){
            $message->to('18569820614@139.com');
            $message->subject('测试');
        });


        $data['password'] = bcrypt('admin123');
        $res = User::create($data);

        return redirect(route('admin.user.list'));

    }

    /**
     * 用户分配角色
     * @param User $user 依赖注入当前用户信息
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function role(User $user,Request $request)
    {
        if($request->isMethod('post')){
            $params = $request->except('_token');

            $user->role_id = $params['ids'];
            $res = $user->save();
            if($res){
                return redirect(route('admin.user.role',$user));
            }else{
                return redirect(route('admin.user.role',$user))->withErrors('添加角色失败');
            }
        }
        $data = Role::all();
        $userRole = $user->role()->value('id');
        return view('admin.user.role',compact('user','data','userRole'));
    }
}
